import subprocess
import re
import smtplib
from email.mime.text import MIMEText
from email.header import Header

# 设置邮件参数
sender = 'xxxxxx@qq.com'  # 发件人邮箱地址，建议发件人和收件人一个地址即可
password = 'gxulhidzypkabcde'  # 发件人邮箱授权码
receiver = 'xxxxxx@qq.com'  # 收件人邮箱地址，建议发件人和收件人一个地址即可
    
def get_ipv6_address_from_ipconfig():
    """ 使用 ipconfig 命令获取IPv6地址及其类型 """
    ipv6_info = {}
    try:
        # 运行 ipconfig 命令并获取输出
        output = subprocess.check_output("ipconfig", encoding='gbk')
        
        # 使用正则表达式匹配IPv6地址和类型
        ipv6_matches = re.finditer(r"   IPv6 地址 . . . . . . . . . . . . : (?P<ipv6>[^\s]+)|"
                                   r"   临时 IPv6 地址. . . . . . . . . . : (?P<temp_ipv6>[^\s]+)|"
                                   r"   本地链接 IPv6 地址 . . . . . . . : (?P<link_local_ipv6>[^\s%]+)", output, re.MULTILINE)
        
        # 处理匹配结果
        for match in ipv6_matches:
            if match.group('ipv6'):
                ipv6_info[match.group('ipv6')] = 'IPv6地址'
            elif match.group('temp_ipv6'):
                ipv6_info[match.group('temp_ipv6')] = '临时IPv6地址'
            elif match.group('link_local_ipv6'):
                ipv6_info[match.group('link_local_ipv6')] = '本地链接IPv6地址'

    except subprocess.CalledProcessError as e:
        print("无法运行 ipconfig 命令", e)

    return ipv6_info

def send_email(subject, body, receiver):
    """ 发送邮件 """
    print("准备发送邮件...")

    message = MIMEText(body, 'plain', 'utf-8')
    message['From'] = sender  # 直接设置发件人地址
    message['To'] = receiver
    message['Subject'] = subject

    try:
        print("正在连接SMTP服务器...")
        smtp_obj = smtplib.SMTP_SSL('smtp.qq.com', 465)
        print("正在登录邮箱...")
        smtp_obj.login(sender, password)
        print("正在发送邮件...")
        smtp_obj.sendmail(sender, [receiver], message.as_string())
        print("邮件发送成功")
    except smtplib.SMTPException as e:
        print("邮件发送失败", e)

def format_ipv6_addresses(ipv6_addrs):
    """ 格式化IPv6地址及其类型为字符串 """
    lines = []
    for ip, ip_type in ipv6_addrs.items():
        line = f"{ip_type}: {ip}"
        lines.append(line)
    return '\n'.join(lines)

def main():
    print("脚本开始执行...")
    # 读取之前的IPv6地址
    try:
        with open('prev_ipv6.txt', 'r') as file:
            prev_ipv6_lines = file.read().splitlines()
        prev_ipv6 = {}
        for line in prev_ipv6_lines:
            colon_pos = line.find(':')  # 找到第一个冒号的位置
            ip_type = line[:colon_pos].strip()  # 获取类型
            ip_address = line[colon_pos+1:].strip()  # 获取IPv6地址
            prev_ipv6[ip_address] = ip_type
        print("读取到之前的IPv6地址: ", prev_ipv6)
    except FileNotFoundError:
        print("未找到之前的IPv6地址文件，将创建新文件。")
        prev_ipv6 = {}
        
    # 获取当前的IPv6地址
    current_ipv6 = get_ipv6_address_from_ipconfig()

    # 检查IPv6地址是否发生变化
    if prev_ipv6 != current_ipv6:
        print("IPv6地址发生变化")
        print("现在的IPv6地址: ", current_ipv6)
        ipv6_info = format_ipv6_addresses(current_ipv6)
        send_email('IPv6地址变更通知', ipv6_info, receiver)

        # 更新保存的IPv6地址
        with open('prev_ipv6.txt', 'w') as file:
            for ip, ip_type in current_ipv6.items():
                file.write(f"{ip_type}: {ip}\n")
    else:
        print("IPv6地址未发生变化，无需更新或发送邮件。")

    print("脚本执行结束。")

if __name__ == "__main__":
    main()